var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();
var http = require('http');
// 解决跨域
const cors = require('cors');
app.use(cors());
// 连接数据库
require('./db/conn_mongodb');

// websocket和http服务器一起用提前创建好传给express-ws，替换/bin/www原有的创建
app.server = http.createServer(app);
require('express-ws')(app, app.server);
// 解决express-ws在路由中不可用问题
const ws = require('./socket/whiteboard');
ws(app)


// 注册将JWT字符串装换成JSON对象的中间件
const {expressjwt: expressJWT} = require("express-jwt")
const secretKey = '2022Hackathon';
app.use('/', expressJWT({
  secret: secretKey,
  algorithms: ['HS256'],
  getToken(req){ // 定义从请求中获取令牌的函数
    // 默认从headers中获取
    if (
        req.headers.authorization &&
        req.headers.authorization.split(" ")[0] === "Bearer"
    ) {
      return req.headers.authorization.split(" ")[1];
    } else if (req.query && req.query.token) {
      // 客户端websocket 无法自定义header从url参数中获取
      return req.query.token;
    }
    return null;
  }
}).unless({
  path: ['/users/login','/users/register','/users/secretSecurity','/users/changePassword']
}));

// Token错误处理
app.use(function (err, req, res, next) {
  if (err.name === "UnauthorizedError") {
    res.send({
      errno: 401,
      message: 'token过期或无效'
    })
  } else {
    next(err);
  }
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
// app.use('/whiteboard', whiteboardRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;